var g_browsers = Object.create(null);

var msAbstractParser = (function()
{
    function MsAbstractParser()
    {
    }

    MsAbstractParser.prototype = {

        parse: function (obj, customArgs)
        {
            console.log("parsing...");

            let args = [];
            let tmpCookies;
            let systemUserAgent;
            let systemBrowser;
            let allowWbCookies = true;
            
            try
            {
                systemUserAgent = qtJsSystem.defaultUserAgent;
                systemBrowser = qtJsSystem.defaultWebBrowser;
                allowWbCookies = App.pluginsAllowWbCookies;
            }
            catch(e) {}

            let proxyUrl = qtJsNetworkProxyMgr.proxyForUrl(obj.url).url();
            if (proxyUrl)
            {
                proxyUrl = proxyUrl.replace(/^https:\/\//i, 'http://'); // FDM bug workaround
                args.push("--proxy", proxyUrl);
            }

            args.push("-J", "--flat-playlist", "--no-warnings", "--compat-options", "no-youtube-unavailable-videos");

            if (allowWbCookies)
            {
                if (obj.cookies && obj.cookies.length)
                {
                    tmpCookies = qtJsTools.createTmpFile("request_" + obj.requestId + "_cookies");
                    if (tmpCookies && tmpCookies.writeText(cookiesToNetscapeText(obj.cookies)))
                        args.push("--cookies", tmpCookies.path);
                }
                else
                {
                    let browser = obj.browser || systemBrowser;
                    if (browser)
                    {
                        if (!(browser in g_browsers))
                        {
                            return this.checkBrowser(obj.requestId, obj.interactive, browser)
                                .then(() => this.parse(obj, customArgs));
                        }
                        else
                        {
                            // In case the current web browser is not supported,
                            // let's try Mozilla Firefox as the most well-supported web browser.
                            if (!g_browsers[browser] && browser !== "firefox")
                            {
                                browser = "firefox";
                                
                                if (!(browser in g_browsers))
                                {
                                    return this.checkBrowser(obj.requestId, obj.interactive, browser)
                                        .then(() => this.parse(obj, customArgs));
                                }
                            }
                            
                            if (g_browsers[browser])
                                args.push('--cookies-from-browser', browser);
                        }
                    }
                }
            }
            
            let userAgent = obj.userAgent || systemUserAgent;
            if (userAgent)
                args.push('--user-agent', userAgent);

            if (customArgs.length)
                args = args.concat(customArgs);

            args.push(obj.url);

            return launchPythonScript(obj.requestId, obj.interactive, "yt-dlp/yt_dlp/__main__.py", args)
            .then(function(obj)
            {
                logPythonResult(obj);

                return new Promise(function (resolve, reject)
                {
                    let output = obj.output.trim();
                    if (!output || output[0] !== '{')
                    {
                        let isUnsupportedUrl = /ERROR:\s*(\[generic\])?\s*Unsupported URL:/.test(obj.errorOutput);
                        reject({
                                   error: isUnsupportedUrl ? "Unsupported URL" : "Parse error",
                                   isParseError: !isUnsupportedUrl
                               });
                    }
                    else
                    {
                        resolve(JSON.parse(output));
                    }
                });
            });
        },

        isSupportedSource: function(url)
        {
            return false;
        },

        supportedSourceCheckPriority: function()
        {
            return 0;
        },

        isPossiblySupportedSource: function(obj)
        {
            if (obj.contentType && !/^text\/html(;.*)?$/.test(obj.contentType))
                return false;
            if (obj.resourceSize !== -1 &&
                    (obj.resourceSize === 0 || obj.resourceSize > 3*1024*1024))
            {
                return false;
            }
            return /^https?:\/\//.test(obj.url);
        },

        overrideUrlPolicy: function(url)
        {
            return true;
        },
        
        minIntevalBetweenQueryInfoDownloads: function()
        {
            return 300;
        },
        
        checkBrowser: function(requestId, interactive, browser)
        {
            console.log("Checking browser support (", browser, ")...");
            
            return launchPythonScript(requestId, interactive, "yt-dlp/yt_dlp/__main__.py", ['--cookies-from-browser', browser, 'e692ec362191442c960a761ac6b84878://test.test'])
            .then(function(obj)
            {
                logPythonResult(obj);

                return new Promise(function (resolve, reject)
                {
                    let isSupported = /"e692ec362191442c960a761ac6b84878"/.test(obj.errorOutput);
                        
                    console.log(browser, " supported: ", isSupported);
                        
                    g_browsers[browser] = isSupported;
                        
                    resolve();
                });
            });
        }
    };

    return new MsAbstractParser();
}());
